package org.eclipse.football;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.football.web.ReadData;

public class LogInServlet extends HttpServlet implements Servlet {

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		

		//get Form data
		String username = request.getParameter("UserName");
		String password = request.getParameter("Password");
		String button = request.getParameter("button");
		
		LogIn user = new LogIn(username, password);
		
		//if the user tries to log in
		if(button.equals("Log-In"))
		{
			//go to stats page if log in info is correct, else stay on log in page
			if(user.isKnown()){
				request.getSession().setAttribute("username", username);
				ReadData.ReadData();
				getServletContext().getRequestDispatcher("/LeagueSummary.jsp").forward(request, response);
			}
			else{ 
				request.getSession().setAttribute("LogInState", "Incorrect User Name and/or Password!");
				getServletContext().getRequestDispatcher("/LogIn.jsp").forward(request, response);
			}
		}
			
		else if(button.equals("Create New Account"))
		{	
			//make sure user doesn't already exist, else add user go to stats page
			if(user.exists())
			{
				request.getSession().setAttribute("LogInState", "User Already Exists!");
				getServletContext().getRequestDispatcher("/LogIn.jsp").forward(request, response);
			}
			else{
				//make sure the user has entered an username and password
				if(username.length()==0||password.length()==0)
				{
					request.getSession().setAttribute("LogInState", "Type in a username and password to create an account.");
					getServletContext().getRequestDispatcher("/LogIn.jsp").forward(request, response);
				}
				else{
					user.add();
					request.getSession().setAttribute("username", username);
					ReadData.ReadData();
					getServletContext().getRequestDispatcher("/LeagueSummary.jsp").forward(request, response);			

				}
			}
		}
		else if(button.equals("Delete Account")){
			if(user.isKnown()){
				user.delete();
				request.getSession().setAttribute("LogInState", "Account Deleted");
				getServletContext().getRequestDispatcher("/LogIn.jsp").forward(request, response);
			}
			else{ 
				request.getSession().setAttribute("LogInState", "Couldn't Delete Account. Log-In Info Incorrect.");
				getServletContext().getRequestDispatcher("/LogIn.jsp").forward(request, response);
			}
		}
		else if(button.equals("Change Account")){
			request.getSession().setAttribute("LogInState", "");
			getServletContext().getRequestDispatcher("/LogIn.jsp").forward(request, response);
		}
	}

}

